package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.hm_FrameWork.view.RefreshLoadmoreLayout;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseAdapter;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.CmnProductionAdapter;
import com.hemaapp.yjnh.adapter.CustomBlogAdapter2;
import com.hemaapp.yjnh.chat.ChatPrivateActivity;
import com.hemaapp.yjnh.listener.OnBlogItemClickListener;
import com.hemaapp.yjnh.bean.Blog;
import com.hemaapp.yjnh.bean.ClientDetails;
import com.hemaapp.yjnh.bean.CustomBlog;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.Img;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.utils.ImageUtils;
import com.hemaapp.yjnh.utils.LoginUtil;
import com.hemaapp.yjnh.view.ShowTextPop;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.view.XtomListView;
import xtom.frame.view.XtomRefreshLoadmoreLayout;
import xtom.frame.view.XtomRefreshLoadmoreLayout.OnStartListener;

/**
 * 别人的田家详情
 *
 * @author ZhangGuiyou
 *         Date:2015-8-12 11:49
 */
public class FarmerDetailsActivity extends BaseActivity implements OnClickListener {

    private TextView titleText;
    private ImageButton titleLeft;
    private Button titleRight;
    private ImageView titleRightImg;
    private RefreshLoadmoreLayout refreshLoadmoreLayout;
    private XtomListView listview;

    private View headerView;
    @Bind(R.id.iv_avatar)
    ImageView ivAvatar;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.ratingBar)
    RatingBar ratingBar;
    @Bind(R.id.tv_address)
    TextView tvAddress;
    @Bind(R.id.tv_consult)
    TextView tvConsult;
    @Bind(R.id.tv_products)
    TextView tvProducts;
    @Bind(R.id.line_products)
    View lineProducts;
    @Bind(R.id.layout_products)
    RelativeLayout layoutProducts;
    @Bind(R.id.tv_customize)
    TextView tvCustomize;
    @Bind(R.id.line_customize)
    View lineCustomize;
    @Bind(R.id.layout_customize)
    RelativeLayout layoutCustomize;

    private ClientDetails details;
    private String client_id;
    private int page;
    private ArrayList<Blog> blogs = new ArrayList<Blog>();
    private ArrayList<CustomBlog> customBlogs = new ArrayList<>();
    private BaseAdapter adapter;
    private User user;
    private LoginUtil.LoginCallBack loginCallBack;
    private int type = 1;//1田家的农货，2田家的定制

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_farmer_detail);
        super.onCreate(savedInstanceState);
        user = getApplicationContext().getUser();
        EventBus.getDefault().register(this);
        init();
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    private void init() {
        headerView = LayoutInflater.from(mContext).inflate(R.layout.header_farmer_detail, null);
        ButterKnife.bind(this, headerView);
        listview.addHeaderView(headerView);
        String token = user == null? "":user.getToken();
        getNetWorker().clientGet(token, client_id);//获取田家详细信息
        getCropsList();
    }

    /**
     * 获取这位田家的农货列表
     */
    private void getCropsList() {
        getNetWorker().blogList("3", client_id, "5", "1", "", "1", "", "", "", "", "", "", "", "", page + "");
    }

    /**
     * 获取田家的定制农货
     */
    private void getCustomList() {
        getNetWorker().getCustomBlogList(client_id, "1", "", "", "0", "1", page+"");
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case CLIENT_GET:
            case BLOG_LIST:
            case CUSTOM_BLOG_LIST:
            case CART_ADD:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case CLIENT_GET:
            case BLOG_LIST:
            case CUSTOM_BLOG_LIST:
            case CART_ADD:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case CLIENT_GET:
                HemaArrayResult<ClientDetails> uResult = (HemaArrayResult<ClientDetails>) baseResult;
                details = uResult.getObjects().get(0);
                setDatas();
                break;
            case BLOG_LIST:
                String page = netTask.getParams().get("page");
                @SuppressWarnings("unchecked")
                HemaPageArrayResult<Blog> bResult = (HemaPageArrayResult<Blog>) baseResult;
                if (bResult == null || bResult.getObjects() == null)
                    return;
                ArrayList<Blog> goods = bResult.getObjects();
                if ("0".equals(page)) {// 刷新
                    refreshLoadmoreLayout.refreshSuccess();
                    refreshLoadmoreLayout.setLoadmoreable(true);
                    blogs.clear();
                    blogs.addAll(goods);
                } else {//加载更多
                    refreshLoadmoreLayout.loadmoreSuccess();
                    if (goods.size() > 0) {
                        blogs.addAll(goods);
                    } else {
                        refreshLoadmoreLayout.setLoadmoreable(false);
                        XtomToastUtil.showShortToast(mContext, "已经到最后啦");
                    }
                }
                refreshDatas(-1);
                break;
            case CUSTOM_BLOG_LIST:
                String page1 = netTask.getParams().get("page");
                @SuppressWarnings("unchecked")
                HemaPageArrayResult<CustomBlog> cResult = (HemaPageArrayResult<CustomBlog>) baseResult;
                if (cResult == null || cResult.getObjects() == null)
                    return;
                if ("0".equals(page1)) {// 刷新
                    refreshLoadmoreLayout.refreshSuccess();
                    refreshLoadmoreLayout.setLoadmoreable(true);
                    customBlogs.clear();
                    customBlogs.addAll(cResult.getObjects());
                } else {//加载更多
                    refreshLoadmoreLayout.loadmoreSuccess();
                    if (cResult.getObjects().size() > 0) {
                        customBlogs.addAll(cResult.getObjects());
                    } else {
                        refreshLoadmoreLayout.setLoadmoreable(false);
                        XtomToastUtil.showShortToast(mContext, "已经到最后啦");
                    }
                }
                refreshDatas(-1);
                break;
            case FOLLOW_COLLECT_SAVEOPERATE:
                ShowTextPop stp = new ShowTextPop(mContext,
                        findViewById(R.id.father));
                String follow = details.getFollowflag();
                if (follow.equals("0")) {//关注成功
                    details.setFollowflag("1");
                    stp.setText("已关注");
                    stp.setDrawable(R.drawable.follow, 0, 0, 0);
                    titleRightImg.setImageResource(R.drawable.heart_while);
                } else if (follow.equals("1")) {//取消关注
                    details.setFollowflag("0");
                    stp.setText("取消关注");
                    stp.setDrawable(R.drawable.unfollow, 0, 0, 0);
                    titleRightImg.setImageResource(R.drawable.heart_while_stroke);
                }
                stp.show();
                break;
            case CART_ADD:
                XtomToastUtil.showShortToast(mContext, "成功添加到购物车");
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case CLIENT_GET:
                showTextDialog("获取商家信息失败，"+baseResult.getMsg());
                titleText.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
                break;
            case BLOG_LIST:
            case CUSTOM_BLOG_LIST:
                if (page == 0) {// 刷新
                    refreshLoadmoreLayout.refreshFailed();
                } else {
                    refreshLoadmoreLayout.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "获取信息失败" + baseResult.getMsg());
                break;
            case FOLLOW_COLLECT_SAVEOPERATE:
                XtomToastUtil.showShortToast(mContext, "操作失败" + baseResult.getMsg());
                break;
            case CART_ADD:
                XtomToastUtil.showShortToast(mContext, "添加到购物车失败，"+baseResult.getMsg());
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case CLIENT_GET:
                showTextDialog("获取信息失败!");
                titleText.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
                break;
            case BLOG_LIST:
            case CUSTOM_BLOG_LIST:
                if (page == 0) {// 刷新
                    refreshLoadmoreLayout.refreshFailed();
                } else {
                    refreshLoadmoreLayout.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "获取信息失败，请稍后再试");
                refreshDatas(failedType);
                break;
            case FOLLOW_COLLECT_SAVEOPERATE:
                XtomToastUtil.showShortToast(mContext, "操作失败，请稍后再试");
                break;
            case CART_ADD:
                XtomToastUtil.showShortToast(mContext, "添加到购物车失败");
                break;
        }
    }

    private void refreshDatas(int failedType) {
        if (null == adapter || page == 0) {
            if (type == 1) {
                adapter = new CmnProductionAdapter(mContext, blogs);
                ((CmnProductionAdapter)adapter).setItemClickListener(new OnBlogItemClickListener() {
                    @Override
                    public void onClickListener(int position) {
                        Intent it = new Intent(mContext, FarmerCropDetailActivity.class);
                        it.putExtra("blog_id", blogs.get(position).getId());
                        mContext.startActivity(it);
                    }

                    @Override
                    public void onCartListener(final int position) {
                        loginCallBack = new LoginUtil.LoginCallBack() {
                            @Override
                            public void onLogin() {
                                getNetWorker().cartAdd(user.getToken(),blogs.get(position).getId(), "1", "0");
                                loginCallBack = null;
                            }
                        };
                        LoginUtil.getInstance(mContext, loginCallBack);
                    }
                });
            }else {
                adapter = new CustomBlogAdapter2(mContext, customBlogs);
            }
            adapter.setEmptyString("暂无商品");
            listview.setAdapter(adapter);
        } else {
            adapter.setEmptyString("暂无商品");
            adapter.notifyDataSetChanged();
        }
        adapter.setFailtype(failedType);
    }

    @Override
    protected void findView() {
        titleText = (TextView) findViewById(R.id.title_text);
        titleLeft = (ImageButton) findViewById(R.id.title_left_btn);
        titleRight = (Button) findViewById(R.id.title_right_btn);
        titleRightImg = (ImageView) findViewById(R.id.title_right_img);

        refreshLoadmoreLayout = (RefreshLoadmoreLayout) findViewById(R.id.refreshLoadmoreLayout);
        listview = (XtomListView) findViewById(R.id.listview);
    }

    @Override
    protected void getExras() {
        client_id = getIntent().getStringExtra("client_id");
    }

    @Override
    protected void setListener() {
        titleText.setText("田家详情");
        titleLeft.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        titleRight.setVisibility(View.GONE);
        titleRightImg.setVisibility(View.VISIBLE);
        titleRightImg.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (user != null) {
                    String token = user.getToken();
                    if ("0".equals(details.getFollowflag())) {//未关注
                        getNetWorker().FolColOperate(token, "1", "1", details.getId());
                    } else {//已关注
                        getNetWorker().FolColOperate(token, "1", "2", details.getId());
                    }
                }else
                    BaseUtil.checkLogin(mContext);
            }
        });

        refreshLoadmoreLayout.setOnStartListener(new OnStartListener() {
            @Override
            public void onStartRefresh(XtomRefreshLoadmoreLayout v) {
                page = 0;
                if (type == 1)
                    getCropsList();
                else
                    getCustomList();
            }

            @Override
            public void onStartLoadmore(XtomRefreshLoadmoreLayout v) {
                page++;
                if (type == 1)
                    getCropsList();
                else
                    getCustomList();
            }
        });
    }

    private void setDatas() {
        ImageUtils.loadAvatar(mContext, details.getAvatar(), ivAvatar);
        tvName.setText(details.getNickname());
        tvAddress.setText(details.getAddress());
        String follow = details.getFollowflag();
        if (follow == null || follow.equals("0")) {//未关注
            titleRightImg.setImageResource(R.drawable.heart_while_stroke);
        } else if (follow.equals("1")) {//已关注
            titleRightImg.setImageResource(R.drawable.heart_while);
        }
        ratingBar.setRating(Float.parseFloat(details.getStarscore()));
    }

    private void reset() {
        tvProducts.setTextColor(getResources().getColor(R.color.text_color_dark_grey));
        lineProducts.setVisibility(View.GONE);
        tvCustomize.setTextColor(getResources().getColor(R.color.text_color_dark_grey));
        lineCustomize.setVisibility(View.GONE);
    }

    @OnClick({R.id.iv_avatar, R.id.tv_consult, R.id.layout_products, R.id.layout_customize})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_avatar:
                if(details == null)
                    break;
                ArrayList<Img> imgs = new ArrayList<Img>();
                Img img = new Img(details.getAvatarbig());
                imgs.add(img);
                Intent intent = new Intent(mContext, ShowLargeImageActivity.class);
                intent.putExtra("imgs", imgs);//所有的图片地址
                intent.putExtra("position", 1);//当前是第几张图片
                startActivity(intent);
                break;
            case R.id.tv_consult:
                loginCallBack = new LoginUtil.LoginCallBack() {
                    @Override
                    public void onLogin() {
                        Intent itChat = new Intent(mContext, ChatPrivateActivity.class);
                        itChat.putExtra("to_client_id", details.getId());
                        itChat.putExtra("to_nickname", details.getNickname());
                        itChat.putExtra("to_avatar", details.getAvatar());
                        startActivity(itChat);
                        loginCallBack = null;
                    }
                };
                LoginUtil.getInstance(mContext, loginCallBack);
                break;
            case R.id.layout_products:
                reset();
                tvProducts.setTextColor(getResources().getColor(R.color.theme_orange));
                lineProducts.setVisibility(View.VISIBLE);
                page = 0;
                type = 1;
                getCropsList();
                break;
            case R.id.layout_customize:
                reset();
                tvCustomize.setTextColor(getResources().getColor(R.color.theme_orange));
                lineCustomize.setVisibility(View.VISIBLE);
                page = 0;
                type = 2;
                getCustomList();
                break;
        }
    }

    @Subscribe
    public void onEventMainThread(EventBusMsg msg) {
        if (msg.getType() == EventBusConfig.USER) {
            this.user = msg.getUser();
            String token = user == null? "":user.getToken();
            getNetWorker().clientGet(token, client_id);//获取田家详细信息
            if (loginCallBack != null)
                loginCallBack.onLogin();
        }
    }
}
